const express = require('express');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const AppCode = require('./config/AppCode');
const UserCount = require('./config/UserCount');
const DeepCopy = require('./utils/deepCopy');
const GetUrl = require('./utils/GetURL');
const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

const router = express.Router();
let appCode = {};
const password =
  'H@5d!J*t5!DS55221!5DF4QqL';

function getUserCount(req) {
  let _userCount = req.params.userCount;
  return DeepCopy({}, UserCount.Public, UserCount[_userCount]);
}
function getAppCode(req) {
  appCode = new AppCode ();
  let _appCode = req.params.appCode;
  if (/\./.test(_appCode)) {
    return '';
  }
  console.log(`${req.ip}   访问appCode：  ${_appCode}   提取码： ${req.body.password === password ? '正确' : req.body.password}  Time:  ${(new Date()).toLocaleTimeString()}`);
  return req.body.password === password ? appCode.get(_appCode, true) : appCode.get(_appCode, false);
}

function appcodeModify(config) {
  config.SSO = GetUrl.getSSO(config.Projects.sso);
  if (config.JavaURL && config.JavaURL.projectName) {
    let JavaProjectName = config.JavaURL.projectName;
    let JavaUrl = GetUrl.getURL(config.JavaURL);
    delete config.JavaURL.projectName;
    let JavaOriginUrl = GetUrl.getURL(config.JavaURL);
    config.Java = {
          url: JavaUrl,
          originUrl: JavaOriginUrl,
          projectName: JavaProjectName,
      };
  }
  config.PublicURL = {
    ...config.LocalURL,
    ...config.PublicURL,
  };
  config.Local = DeepCopy({
    api: GetUrl.getURL(config.PublicURL),
    url: GetUrl.getURL({}, config.PublicURL, config.Project),
    interface: `http://${config.PublicURL.origin}:${config.PublicURL.port}/${config.Project.appCode}`,
    none: `http://${config.PublicURL.origin}:${config.PublicURL.port}`
  }, config.Project);
  if(config.Local.name !== 'SSO' && config.Local.name !== 'devJava' ){
    delete config.Projects;
  }
  delete config.Project;
  delete config.JavaURL;
  delete config.URL;
  console.log(JSON.stringify(config));
  return config;
}

function UserAppcode(req, res) {
  let appCode = getAppCode(req);
  if (appCode) {
    return res.json(appcodeModify(DeepCopy(appCode, getUserCount(req))));
  } else {
    return res.send('null');
  }
}
function Appcode(req, res) {
  let appCode = getAppCode(req);
  if (appCode) {
    return res.json(appcodeModify(appCode));
  } else {
    return res.send('null');
  }
}

router.post('/:userCount/:appCode', (req, res, next) => { UserAppcode(req, res); });
router.get('/:userCount/:appCode', (req, res, next) => { UserAppcode(req, res); });

router.post('/:appCode', (req, res, next) => { Appcode(req, res) });
router.get('/:appCode', (req, res, next) => { Appcode(req, res) });
app.use(router);

module.exports = app;
